package com.ruoyi.ghxx.controller;

import java.io.File;
import java.io.InputStream;
import java.util.*;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.ghxx.aop.SysInitData;
import com.ruoyi.ghxx.aop.SysInitUpdateData;
import com.ruoyi.ghxx.aop.SysQueryData;
import com.ruoyi.ghxx.modelVo.BArea;
import com.ruoyi.ghxx.service.IBDeviceRealDataService;
import com.ruoyi.ghxx.service.impl.RedisServiceImpl;
import com.ruoyi.ghxx.util.Detect;
import com.ruoyi.ghxx.util.ImageUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.ghxx.domain.BDeviceZt;
import com.ruoyi.ghxx.service.IBDeviceZtService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;

/**
 * 云组态Controller
 *
 * @author ruoyi
 * @date 2022-05-21
 */
@RestController
@RequestMapping("/ghxx/bDeviceZt")
public class BDeviceZtController extends BaseController
{
    @Autowired
    private IBDeviceZtService bDeviceZtService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
/**
 * 查询云组态列表
 */
    @GetMapping("/list")
    @SysQueryData
    public TableDataInfo list(BDeviceZt bDeviceZt)
    {
        startPage();
        if(Detect.notEmpty(bDeviceZt.getQueryDeptId())){
            bDeviceZt.setDeptIdStrs(bDeviceZt.getQueryDeptId());
        }
        List<BDeviceZt> list =bDeviceZtService.selectBDeviceZtList(bDeviceZt);
        return getDataTable(list);
    }
    @GetMapping("/getZtData")
    @SysQueryData
    public AjaxResult getZtData(BDeviceZt bDeviceZt)
    {
        if(Detect.notEmpty(bDeviceZt.getQueryDeptId())){
            bDeviceZt.setDeptIdStrs(bDeviceZt.getQueryDeptId());
        }
        if(Detect.isEmpty(bDeviceZt.getGuid())){
            return AjaxResult.error("系统中无此组态界面！");
        }
        BeanPropertyRowMapper<BDeviceZt> bDeviceDetailMapper = new BeanPropertyRowMapper<>(BDeviceZt.class);
        String sql="select device_mac, device_name, page_name,device_zt_data from b_device_zt where guid=?";
        try {
            bDeviceZt = jdbcTemplate.queryForObject(sql, bDeviceDetailMapper,bDeviceZt.getGuid());//处理结果集EmptyResultDataAccessException，不做任何操作
        }catch (EmptyResultDataAccessException e){
        }
        return AjaxResult.success(bDeviceZt);
    }
    /**
     * 导出云组态列表
     */
    @Log(title = "云组态", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @SysQueryData
    public AjaxResult export(BDeviceZt bDeviceZt)
    {
        List<BDeviceZt> list = bDeviceZtService.selectBDeviceZtList(bDeviceZt);
        ExcelUtil<BDeviceZt> util = new ExcelUtil<BDeviceZt>(BDeviceZt.class);
        return util.exportExcel(list, "bDeviceZt");
    }

    /**
     * 获取云组态详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(bDeviceZtService.selectBDeviceZtById(id));
    }

    /**
     * 新增云组态
     */
    @Log(title = "云组态", businessType = BusinessType.INSERT)
    @PostMapping
    @SysInitData
    @Transactional
    public AjaxResult add(@RequestBody BDeviceZt bDeviceZt)
    {
        if(bDeviceZt.getIsMainPage()!=null&&bDeviceZt.getIsMainPage()==1&&Detect.notEmpty(bDeviceZt.getDeviceMac())){
            String ztSql="update b_device_zt set is_main_page =0 where device_mac=?";
            jdbcTemplate.update(ztSql,bDeviceZt.getDeviceMac());
        }
        if(Detect.notEmpty(bDeviceZt.getPageSize())&&bDeviceZt.getPageSize().indexOf("x")>-1){
            String[] pageSizes = bDeviceZt.getPageSize().split("x");
            bDeviceZt.setDeviceZtData("{ \"name\": \"--\", \"layer\": { \"backColor\": \"\", \"backgroundImage\": \"\", \"widthHeightRatio\": \"\", \"width\": "+pageSizes[0]+", \"height\": "+pageSizes[1]+" }, \"components\": [] }");
        }
        return toAjax(bDeviceZtService.insertBDeviceZt(bDeviceZt));
    }

    /**
     * 修改云组态
     */
    @Log(title = "云组态", businessType = BusinessType.UPDATE)
    @PutMapping
    @SysInitUpdateData
    @Transactional
    public AjaxResult edit(@RequestBody BDeviceZt bDeviceZt)
    {
        if(bDeviceZt.getIsMainPage()!=null&&bDeviceZt.getIsMainPage()==1&&Detect.notEmpty(bDeviceZt.getDeviceMac())){
            String ztSql="update b_device_zt set is_main_page =0 where device_mac=? and guid!=?";
            jdbcTemplate.update(ztSql,bDeviceZt.getDeviceMac(),bDeviceZt.getGuid());
        }
        return toAjax(bDeviceZtService.updateBDeviceZt(bDeviceZt));
    }

    /**
     * 删除云组态
     */
    @Log(title = "云组态", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bDeviceZtService.deleteBDeviceZtByIds(ids));
    }
    /*
    * 保存组态信息
    * */
    @PostMapping(value = "saveZt")
    @SysInitData
    public AjaxResult saveZt(@RequestBody BDeviceZt bDeviceZt)
    {
        if(Detect.isEmpty(bDeviceZt.getGuid())){
            return AjaxResult.error("参数不符合规定");
        }
        BDeviceZt bDeviceZtQuery=new BDeviceZt();
        bDeviceZtQuery.setGuid(bDeviceZt.getGuid());
        List<BDeviceZt> bDeviceZts = bDeviceZtService.selectBDeviceZtList(bDeviceZtQuery);
        if(bDeviceZts.size()>0){
            BDeviceZt deviceZt = bDeviceZts.get(0);
            deviceZt.setDeviceZtData(bDeviceZt.getDeviceZtData());
            bDeviceZtService.updateBDeviceZt(deviceZt);
        }else{
            bDeviceZtService.insertBDeviceZt(bDeviceZt);
        }
        return AjaxResult.success();
    }
    @PostMapping("/importZtJson")
    public AjaxResult importZtJson(@RequestBody MultipartFile file,String guid) throws Exception{
        InputStream inputStream = file.getInputStream();
        if(file.isEmpty()){
            return AjaxResult.error("无效的配置文件");
        }
        if(file.getOriginalFilename().indexOf("json")==-1){
            return AjaxResult.error("无效的配置文件");
        }
        BDeviceZt bDeviceZt=new BDeviceZt();
        try {
             bDeviceZt = JSON.parseObject(inputStream, BDeviceZt.class);
        }catch (Exception e){
            return AjaxResult.error("无效的配置文件");
        }finally {
            inputStream.close();
        }
        String ztData=bDeviceZt.getDeviceZtData();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String deptIds=","+loginUser.getUser().getDept().getAncestors()+","+loginUser.getUser().getDeptId()+",";
        if(Detect.isEmpty(guid)){
            guid=UUID.randomUUID().toString();
            bDeviceZt.setId(null);
            bDeviceZt.setGuid(guid);
            bDeviceZt.setPageName(bDeviceZt.getPageName());
            bDeviceZt.setDeviceZtData(ztData);
            bDeviceZt.setIsMainPage(0);
            bDeviceZt.setIsShare(0);
            bDeviceZt.setShareUrl("");
            bDeviceZt.setDeptIdStrs(deptIds);
            bDeviceZt.setCreateBy(loginUser.getUsername());
            bDeviceZt.setCreateTime(new Date());
            bDeviceZt.setUpdateBy(loginUser.getUsername());
            bDeviceZt.setUpdateTime(new Date());
            bDeviceZtService.insertBDeviceZt(bDeviceZt);
        }else {
            BDeviceZt bDeviceZtQuery=new BDeviceZt();
            bDeviceZtQuery.setGuid(guid);
            List<BDeviceZt> bDeviceZts = bDeviceZtService.selectBDeviceZtList(bDeviceZtQuery);
            if(bDeviceZts.size()>0){
                bDeviceZtQuery=bDeviceZts.get(0);
            }
            bDeviceZtQuery.setDeviceZtData(ztData);
            bDeviceZtService.updateBDeviceZt(bDeviceZtQuery);
        }
        return AjaxResult.success("导入成功");
    }
    /*验证分享密码*/
    @PostMapping("/confirmPass")
    public AjaxResult importZtJson(@RequestBody BDeviceZt bDeviceZt) throws Exception{
        if(Detect.isEmpty(bDeviceZt.getGuid())||Detect.isEmpty(bDeviceZt.getDeviceMac())||Detect.isEmpty(bDeviceZt.getSharePass())){
            return AjaxResult.success(false);
        }
        BDeviceZt bDeviceZtQuery= new BDeviceZt();
        bDeviceZtQuery.setDeviceMac(bDeviceZt.getDeviceMac());
        bDeviceZtQuery.setGuid(bDeviceZt.getGuid());
        List<BDeviceZt> bDeviceZtList = bDeviceZtService.selectBDeviceZtList(bDeviceZtQuery);
        if(bDeviceZtList.size()>0){
            if(Detect.notEmpty(bDeviceZtList.get(0).getSharePass())&&bDeviceZtList.get(0).getSharePass().equals(bDeviceZt.getSharePass())){
                return AjaxResult.success(true);
            }else{
                return AjaxResult.success(false);
            }
        }else{
            return AjaxResult.success(false);
        }
    }
    /*
     * 保存组态缩略图
     * */
    @PostMapping(value = "saveZtImage")
    public AjaxResult saveZtImage(@RequestBody BDeviceZt bDeviceZt)
    {
        if(Detect.isEmpty(bDeviceZt.getGuid())){
            return AjaxResult.error("参数不符合规定");
        }
        MultipartFile image =ImageUtils.base64ToMultipartFile(bDeviceZt.getBase64());
        String imageUrl="";
        try{
            imageUrl = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), image);
        }catch (Exception e){
            return AjaxResult.error(500,"上传组件异常，"+e.toString());
        }
        BDeviceZt bDeviceZtQuery=new BDeviceZt();
        bDeviceZtQuery.setGuid(bDeviceZt.getGuid());
        List<BDeviceZt> bDeviceZts = bDeviceZtService.selectBDeviceZtList(bDeviceZtQuery);
        if(bDeviceZts.size()>0){
            BDeviceZt deviceZt = bDeviceZts.get(0);
            if(Detect.notEmpty(deviceZt.getPageImage())){
                String newUrl = deviceZt.getPageImage().replace("/profile", "").replace("/avatar", "");
                File fileQuery=new File(RuoYiConfig.getAvatarPath()+newUrl);
                if(fileQuery.exists()){
                    System.out.println("删除之前的图片资源");
                    fileQuery.delete();
                }
            }
            deviceZt.setPageImage(imageUrl);
            bDeviceZtService.updateBDeviceZt(deviceZt);
        }
        return AjaxResult.success();
    }
    /*打包部署*/
    @PostMapping("/downloadZtZip")
    public AjaxResult download(@RequestBody BDeviceZt bDeviceZt){
        String downloadUrl = bDeviceZtService.download(bDeviceZt);
        return AjaxResult.success(downloadUrl);
    }
    /*获取省市区*/
    @GetMapping("/getArea")
    public AjaxResult getArea(BArea bArea){
        if(bArea.getLvl()==1){
            String sql="SELECT DISTINCT provinceZh from city where countryZh='中国'";
            BeanPropertyRowMapper<BArea> bDeviceMaintainRowMapper = new BeanPropertyRowMapper<>(BArea.class);
            List<BArea> bAreaList = jdbcTemplate.query(sql, bDeviceMaintainRowMapper);
            return AjaxResult.success(bAreaList);
        }else if(bArea.getLvl()==2){
            String sql="SELECT  DISTINCT leaderZh from city where provinceZh=? ";
            BeanPropertyRowMapper<BArea> bDeviceMaintainRowMapper = new BeanPropertyRowMapper<>(BArea.class);
            List<BArea> bAreaList = jdbcTemplate.query(sql, bDeviceMaintainRowMapper,bArea.getProvinceZh());
            return AjaxResult.success(bAreaList);
        }else{
            String sql=" SELECT * from city where leaderZh=?";
            BeanPropertyRowMapper<BArea> bDeviceMaintainRowMapper = new BeanPropertyRowMapper<>(BArea.class);
            List<BArea> bAreaList = jdbcTemplate.query(sql, bDeviceMaintainRowMapper,bArea.getLeaderZh());
            return AjaxResult.success(bAreaList);
        }
    }
}
